package com.android.zgx.calllog;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.widget.TextView;

public class Main extends Activity {
	/*
	 * Variable Definition
	 */
	private TextView mResultText;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		init();
		readCallLog();
	}

	// initialize control
	private void init() {
		mResultText=(TextView)findViewById(R.id.resultText);
	}

	// Android Call Log
	private void readCallLog() {
		// Variable Definition
		String cachedName = "";
		String phoneNumber="";
		int type;
		String time = "";
		int durationSeconds;

		// Access to the Content
		ContentResolver cr = getContentResolver();
		
		// Query for Call Log
		final Cursor cursor = cr.query(CallLog.Calls.CONTENT_URI, new String[] {
				CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME,
				CallLog.Calls.TYPE, CallLog.Calls.DATE, CallLog.Calls.DURATION }, null, null,
				CallLog.Calls.DEFAULT_SORT_ORDER);
		
		// Work with Records
		String tmpStr="";
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			phoneNumber = cursor.getString(0);
			cachedName = cursor.getString(1);
			type = cursor.getInt(2);
			SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			Date date = new Date(Long.parseLong(cursor.getString(3)));
			time = sfd.format(date);
			durationSeconds= cursor.getInt(4);
			
			tmpStr+=phoneNumber+","+cachedName+","+type+","+time+","+durationSeconds+"\r\n";
		}
		mResultText.setText(tmpStr);
	}
}
